<template>
  <ElDialog v-model="visible" :title="dialogType === 'add' ? '新增角色' : '编辑角色'" width="30%" align-center
    @close="handleClose">
    <ElForm ref="formRef" :model="form" :rules="rules" label-width="120px">
      <ElFormItem label="角色名称" prop="name">
        <ElInput v-model="form.name" placeholder="请输入角色名称" />
      </ElFormItem>
      <ElFormItem label="描述" prop="desc">
        <ElInput v-model="form.desc" type="textarea" :rows="3" placeholder="请输入角色描述" />
      </ElFormItem>
      <ElFormItem label="启用">
        <ElSwitch v-model="form.status" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="handleClose">取消</ElButton>
        <ElButton type="primary" @click="handleSubmit">提交</ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { createRole, updateRole } from '@/api/system/role'

type RoleListItem = Api.SystemManage.RoleListItem

interface Props {
  modelValue: boolean
  dialogType: 'add' | 'edit'
  roleData?: RoleListItem
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  dialogType: 'add',
  roleData: undefined
})

const emit = defineEmits<Emits>()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const formRef = ref<FormInstance>()

const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  desc: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
})

const form = reactive<RoleListItem>({
  id: 0,
  name: '',
  desc: '',
  create_time: '',
  status: 1,
  enabled: true
})

// 监听弹窗打开，初始化表单数据
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      initForm()
    }
  },
  { immediate: true }
)

// 监听角色数据变化
watch(
  () => props.roleData,
  (newData) => {
    if (newData && props.modelValue) {
      initForm()
    }
  },
  { deep: true }
)

const initForm = () => {
  if (props.dialogType === 'edit' && props.roleData) {
    Object.assign(form, {
      id: props.roleData.id,
      name: props.roleData.name,
      desc: props.roleData.desc,
      create_time: props.roleData.create_time,
      status: props.roleData.status
    })
  } else {
    Object.assign(form, {
      id: 0,
      roleName: '',
      desc: '',
      create_time: '',
      status: 1
    })
  }
}

const handleClose = () => {
  visible.value = false
  formRef.value?.resetFields()
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    // 构建请求体（与接口类型对齐）
    const payload = {
      id: form.id,
      name: form.name,
      desc: form.desc,
      status: Boolean(form.status)
    }

    if (props.dialogType === 'add') {
      await createRole(payload)
    } else {
      const id = Number(props.roleData?.id || form.id)
      if (!id) {
        ElMessage.error('缺少角色ID，无法编辑')
        return
      }
      await updateRole(id, payload)
    }

    emit('success')
    handleClose()
  } catch (error) {
    console.log('表单验证失败:', error)
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}
</style>
